$(function () {
    $("#jqGrid").jqGrid({
        url: '../sys/group/list',
        datatype: "json",
        colModel: [			
			{ label: '组名称', name: 'name', index: "name", width: 75 },
            { label: '状态', name: 'deleteStatus', width: 80, formatter: function(value, options, row){
                return value == 0 ?
                    '<span class="label label-success">正常</span>' :
                    '<span class="label label-danger">禁用</span>';
            }},
			{ label: '描述', name: 'groupDesc', width: 100 },
			{ label: '代码', name: 'flowCode', width: 100 }
			// { label: '创建时间', name: 'createTime', index: "create_time", width: 80}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });


});

var setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "id",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	},
	check:{
		enable:true,
		nocheckInherit:true
	}
};
var ztree;
var ztree2;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			name: null,
            userName : null
		},
		showList: true,
		title:null,
		group:{},
		groupUserList:[],
        roleList:{},
        // selectGroupUser : []
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
            //清空表格
            $("#groupUser").jqGrid('clearGridData');
			vm.showList = false;
			vm.title = "新增";
			vm.group = {};
            vm.roleList = {};
            vm.group = {roleIdList:[]};
			vm.getMenuTree(null);
            vm.renderUserTable(null);
            //获取角色信息
            this.getRoleList();
		},
		update: function () {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			
			vm.showList = false;
            vm.title = "修改";
            vm.getMenuTree(id);
            //获取角色信息
            this.getRoleList();
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要禁用选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../sys/group/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
                            toast(r.msg,function(){
                                vm.reload();
                            });
						}else{
                            alertMsg(r.msg);
						}
					}
				});
			});
		},
        enabled: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要启用选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../sys/group/enabled",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
                            toast(r.msg,function(){
                                vm.reload();
                            });
						}else{
                            alertMsg(r.msg);
						}
					}
				});
			});
		},
		getGroup: function(id){
            $.get("../sys/group/info/"+id, function(r){
            	vm.group = r.group;
            	vm.renderUserTable(id)
                //勾选组所拥有的用户
                var userIds = vm.group.userIdList;
                for(var i=0; i<userIds.length; i++) {

                }
                //勾选组关联的业务系统
                var operationIds = vm.group.operationIdList;
                for(var i=0; i<operationIds.length; i++) {
                    var node = ztree2.getNodeByParam("id", operationIds[i]);
                    ztree2.checkNode(node, true, false);
                }
    		});
		},
        renderUserTable:function(groupId){
			//清空表格
			$("#groupUser").jqGrid('clearGridData');
			var page = $("#groupUser").jqGrid('getGridParam','page');
			$("#groupUser").jqGrid('setGridParam',{
				postData:{'groupId': groupId},
				page:page
			}).trigger("reloadGrid");
			$("#groupUser").jqGrid({
				url :'../sys/user/groupUser',
				datatype: 'json',
				postData: {
					'groupId' : groupId
				},
				colModel: [
					{ label: '姓名', name: 'userName', width: 75 },
					{ label: '登陆名', name: 'loginName', width: 75 },
					{ label: '部门', name: 'baName', width: 75 },
					{ label: '手机号', name: 'phone', width: 100 }
				],
				viewrecords: true,
				height: 'auto',
				rowNum: 5,
				rownumbers: true,
				rownumWidth: 25,
				autowidth:true,
				multiselect: true,
				pager: "#groupUserPager",
				pagerpos:'right',
				recordpos:'left',
				jsonReader : {
					root: "page.list",
					page: "page.currPage",
					total: "page.totalPage",
					records: "page.totalCount"
				},
				prmNames : {
					page:"page",
					rows:"limit",
					order: "order"
				},
				gridComplete:function(){
					//隐藏grid底部滚动条
					$("#groupUser").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
				}
			}).trigger("reloadGrid");
		},
		saveOrUpdate: function (event) {
            //获取选择的组织
            var operationNodes = ztree2.getChangeCheckedNodes(true);
			var operationIdList = new Array();
			for (var i=0; i<operationNodes.length;i++){
				var status = operationNodes[i].getCheckStatus();
				if(status.half){
				    continue;
                }
				operationIdList.push(operationNodes[i].id);
			}
            vm.group.operationIdList = operationIdList;
			//获取组成员
            vm.group.userIdList = $("#groupUser").jqGrid("getDataIDs");
			var url = vm.group.id == null ? "../sys/group/save" : "../sys/group/update";
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.group),
			    success: function(r){
                    if(r.code == 0){
                        if(vm.group.id==null){
                            alert(r,function (index,layer) {
                                vm.reload();
                            },function (index) {
                                vm.group.name='';
                                vm.group.remark='';
                            })
                        }else{
                            toast(r.msg,function(){
                                vm.reload();
                            });
                        }

                    }else{
                        alertMsg(r.msg);
                    }
				}
			});
		},
		getMenuTree: function(id) {
			//加载菜单树
			$.get("../sys/menu/perms", function(r){
				ztree = $.fn.zTree.init($("#menuTree"), setting, r.menuList);
				//展开所有节点
				//ztree.expandAll(true);
				if(id != null){
					vm.getGroup(id);
				}
			});
            //加载资源树
            $.get("../sys/operation/operationTree", function(r){
                ztree2 = $.fn.zTree.init($("#operationTree"), setting, r.operationTree);
                //展开所有节点
                //ztree.expandAll(true);
            });
	    },
		getGroupUser: function(id){

		},
        getRoleList: function(){
            $.get("../sys/role/select", function(r){
                vm.roleList = r.list;
            });
        },
	    reload: function (event) {
	    	vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'name': vm.q.name},
                page:page
            }).trigger("reloadGrid");
		},
        addGroupUser : function () {
            vm.q.userName = null;
            $("#groupUser_table").jqGrid('clearGridData');
            var page = $("#groupUser_table").jqGrid('getGridParam','page');
            $("#groupUser_table").jqGrid('setGridParam',{
                postData:{'userName': vm.q.userName},
                page:page
            }).trigger("reloadGrid");
            $("#groupUser_table").jqGrid({
                url: '../sys/user/list',
                datatype: "json",
                colModel: [
                    { label: '姓名', name: 'userName', width: 75 },
                    { label: '登陆名', name: 'loginName', width: 75 },
                    { label: '部门', name: 'baName', width: 75 },
                    { label: '机构', name: 'bapName', width: 75 },
                    { label: '邮箱', name: 'email', width: 90 },
                    { label: '手机号', name: 'phone', width: 100 },
                    { label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
                            return value == 0 ?
                                '<span class="label label-success">正常</span>' :
                                '<span class="label label-danger">禁用</span>';
                        }},
                    { label: '创建时间', name: 'createTime', index: "create_time", width: 80}
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,

                pager: "#groupUser_pager",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                // onSelectRow : function(rowid,status){
                //     if(status){
                //         var rowData = $("#groupUser_table").jqGrid("getRowData",rowid);
                //         vm.selectGroupUser.push(rowData);
                //     }
                // },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            var groupUserWindow = layer.open({
                type: 1,
                title: "增加组内用户",
                maxmin:true,
                area: ["80%", "70%"],
                content: $("#updateGroupUser"),
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var userIds = getSelectedRows('groupUser_table');
                    if(userIds == null){
                        return ;
                    }
                    for (var i = 0; i < userIds.length; i++) {
                        var rowData = $("#groupUser_table").jqGrid("getRowData",userIds[i]);
                        // vm.selectGroupUser.push(rowData);
                        $("#groupUser").jqGrid("addRowData", userIds[i], rowData, "first");
                    }
                    layer.close(groupUserWindow);

                },
                btn2: function(index, layero){
                    console.log('取消回调')
                },
                cancel: function(){
                    console.log('右上角回调')
                }
            });
        },
        deleteGroupUser : function () {
            var userIds = getSelectedRows('groupUser');
            if(userIds == null){
                return ;
            }
            for (var i = 0; i < userIds.length; i++) {
                var ztreeElement = userIds[i];
                $("#groupUser").jqGrid('delRowData',userIds[i]);
            }

        },
        queryGroupUser: function () {
            var page = $("#groupUser_table").jqGrid('getGridParam','page');
            $("#groupUser_table").jqGrid('setGridParam',{
                postData:{'userName': vm.q.userName},
                page:page
            }).trigger("reloadGrid");
        }
	}
});